/**
 * Copyright (c) 2016-2019 优博信息科技 All rights reserved.
 *
 * https://www.jnyoubo.com
 *
 * 版权所有，侵权必究！
 */

package com.youbo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youbo.common.exception.RRException;
import com.youbo.common.utils.RedisUtils;
import com.youbo.common.validator.Assert;
import com.youbo.dao.UserDao;
import com.youbo.entity.TokenEntity;
import com.youbo.entity.UserEntity;
import com.youbo.form.LoginForm;
import com.youbo.service.TokenService;
import com.youbo.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
	@Autowired
	private TokenService tokenService;
	@Autowired
	private RedisUtils redisUtils;


	@Override
	public UserEntity queryByMobile(String mobile,Integer tokenType) {
		UserEntity user=baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
		if(null!=user){
			user.setTokenEntity(tokenService.queryByToken(user.getUserId(),tokenType));
			redisUtils.set(RedisUtils.MY_USER+user.getUserId(),user);
		}
		return user;
	}


	public UserEntity getById(Serializable id,Integer tokenType) {
		UserEntity user=redisUtils.get(RedisUtils.MY_USER+id,UserEntity.class);
		if(null!=user){
			return user;
		}
		user=super.getById(id);
		if(null!=user){
			user.setTokenEntity(tokenService.queryByToken(user.getUserId(),tokenType));
			redisUtils.set(RedisUtils.MY_USER+user.getUserId(),user);
		}
		return user;
	}



	@Override
	public Map<String, Object> login(LoginForm form) {

		UserEntity user = queryByMobile(form.getMobile(),form.getTokenType());

		Assert.isNull(user, "手机号或密码错误");

		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
			throw new RRException("手机号或密码错误");
		}

		//获取登录token
		Map<String, Object> map = new HashMap<>(2);
		TokenEntity tokenEntity = tokenService.createToken(user.getUserId(),form.getTokenType());
		map.put("token", tokenEntity.getToken());
		map.put("expire", tokenEntity.getExpireTime().getTime() - System.currentTimeMillis());

		return map;
	}

}
